import 'package:flutter/material.dart';

class TextFieldWidgetPage extends StatefulWidget {
  @override
  _TextFieldWidgetPageState createState() => _TextFieldWidgetPageState();
}

class _TextFieldWidgetPageState extends State<TextFieldWidgetPage> {
  final TextEditingController _controller = TextEditingController();
  final GlobalKey _globalKey = GlobalKey<FormState>();
  String username, password;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //1.设置默认值
    _controller.text = 'Hello World';
    //2.监听
    _controller.addListener(() {
      print('_controller:${_controller.text}');
    });
  }

  void registerForm() {
    // _globalKey.currentState.save();
    print("username:$username password:$password");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('TextFieldWidgetPage'),
        ),
        body: Container(
            padding: EdgeInsets.all(10),
            child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              TextField(
                decoration: InputDecoration(
                    icon: Icon(Icons.people),
                    labelText: 'username',
                    hintText: '请输入用户名',
                    border: InputBorder.none,
                    filled: true,
                    fillColor: Colors.white),
                controller: _controller,
                onChanged: (value) {
                  print('onChanged:$value');
                },
                onSubmitted: (value) {
                  print('onSubmit:$value');
                },
              ),

              ///注册页面
              Form(
                  key: _globalKey,
                  child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                    TextFormField(
                        decoration: InputDecoration(labelText: '用户名或手机号', icon: Icon(Icons.people)),
                        onSaved: (value) {
                          this.username = value;
                        }),
                    TextFormField(
                        obscureText: false,
                        decoration: InputDecoration(icon: Icon(Icons.lock), labelText: '密码'),
                        onSaved: (value) {
                          this.password = value;
                        }),
                    SizedBox(height: 16),
                    Container(
                        color: Colors.lightBlue,
                        height: 44,
                        child: ElevatedButton(
                            child: Text('注册',
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 18, fontWeight: FontWeight.bold)),
                            onPressed: () => registerForm()))
                  ]))
            ])));
  }
}
